package cn.edu.lingnan.filter;


import cn.edu.lingnan.context.BaseContext;
import cn.edu.lingnan.user.dtos.Result;
import cn.edu.lingnan.utils.JwtUtils;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURL().toString();
        log.info("请求 URL: {}", url);


        if (url.contains("login")||url.contains("register") || url.contains("verify") || url.contains("captcha")
        ||url.contains("have-email")) {
            log.info("这是一个登录请求");
            return true;
        }

        String jwt = request.getHeader("Authorization");
        log.info("Token: {}", jwt);
        if (jwt != null && jwt.startsWith("Bearer ")) {
            jwt = jwt.substring(7); // 移除 "Bearer "前缀
        }

        if (!StringUtils.hasLength(jwt)) {
            log.info("令牌为空");
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            Result error = Result.unauthorized("没有登录");
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);

            return false;
        }

        // 解析令牌
        try {
            Claims claims = JwtUtils.parseJWT(jwt);
         Integer userId = Integer.valueOf(claims.get("userId").toString()); // 验证令牌有效性
            BaseContext.setCurrentId(userId);
            log.info("当前用户 ID: {}", userId);
        } catch (Exception e) {
            log.error("无法解析令牌", e);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            Result error = Result.unauthorized("令牌无效");
            String notLogin = JSONObject.toJSONString(error);
            response.getWriter().write(notLogin);
            return false;
        }

        log.info("令牌有效");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // This can be used for cleanup after the request has been completed
    }
}
